﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using Image = iTextSharp.text.Image;

namespace embImage2Pdf
{
    public class Image2Pdf
    {
       
        /// <summary>
        /// Initializes a new instance of the <see cref="Image2Pdf"/> class.
        /// </summary>
        public Image2Pdf()
        {
            
        }


        /// <summary>
        /// Creates the PDF.
        /// </summary>
        /// <param name="imageData">The image data.</param>
        /// <returns></returns>
        public byte[] CreatePdf(byte[] imageData)
        {
            byte[] result;
            using (MemoryStream ms = new MemoryStream())
            {
                Document pDoc = new Document(PageSize.A4, 0, 0, 0, 0);
                PdfWriter writer = PdfWriter.GetInstance(pDoc, ms);
                pDoc.Open();
                PdfContentByte cb = writer.DirectContent;
                RandomAccessFileOrArray rfa = new RandomAccessFileOrArray(imageData);
                iTextSharp.text.Image img = iTextSharp.text.pdf.codec.TiffImage.GetTiffImage(rfa, 1);
                img.SetAbsolutePosition(0, 0);
                img.ScaleAbsolute(594f, 842f);
                cb.AddImage(img);
                pDoc.Close();
                result = ms.GetBuffer();
            }

            return result;
        }

        /// <summary>
        /// Byteses to bitmap.
        /// </summary>
        /// <param name="byteArray">The byte array.</param>
        /// <returns></returns>
        public static Bitmap BytesToBitmap(byte[] byteArray)
        {
            using (MemoryStream ms = new MemoryStream(byteArray))
            {
                Bitmap img = (Bitmap) System.Drawing.Image.FromStream(ms);


                return img;
            }
        }

        /// <summary>
        /// Images to byte array.
        /// </summary>
        /// <param name="imageIn">The image in.</param>
        /// <returns></returns>
        public byte[] ImageToByteArray(System.Drawing.Image imageIn)
        {
            MemoryStream ms = new MemoryStream();
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Tiff);
            return ms.ToArray();
        }
    }
}